package moonhy.c2dm_client;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;

import moonhy.c2dm_client.AccountActivity.memDues;
import moonhy.c2dm_client.dw.MemberData;
import moonhy.c2dm_client.dw.NoticeData;
import moonhy.c2dm_client.util.JSONSharedPreferences;
import moonhy.c2dm_client.util.httpConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.taptwo.android.widget.TitleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.PhoneNumberUtils;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class MainViewFlowActivity extends Activity {
	NoticeData tmp_nd = new NoticeData();
	ArrayList<MemberData> md_array = new ArrayList<MemberData>();

	private ViewFlow viewFlow;
	private ListView listView;
	
	private SharedPreferences prefs;
	
	private String PHONE_NO;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_viewflow_main);
        Bundle extras = this.getIntent().getExtras();
        
        PHONE_NO = getString(R.string.PHONE);
        
		viewFlow = (ViewFlow) findViewById(R.id.viewflow);
        MainViewFlowAdapter adapter = new MainViewFlowAdapter(this);
        viewFlow.setAdapter(adapter, 1);
		TitleFlowIndicator indicator = (TitleFlowIndicator) findViewById(R.id.viewflowindic);
		indicator.setTitleProvider(adapter);
		viewFlow.setFlowIndicator(indicator);
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
				
		/*
		 *  회칙 화면 설정 시작
		 */
		try {
			JSONObject json_result = JSONSharedPreferences.loadJSONObject(this, "gline", "groupInfo");
			TextView groupIntro = (TextView)findViewById(R.id.groupIntro);
			groupIntro.setText(json_result.getString("GROUP_INTRO"));
			
			TextView groupPolicy = (TextView)findViewById(R.id.groupPolicy);
			groupPolicy.setText(json_result.getString("GROUP_POLICY"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
    @Override
    public void onStart(){
    	super.onResume();
		/*
		 *  홈 화면 설정 시작
		 */
		drawUI(this);
		new initMainPage(this).execute();
		
		
		/*
		 *  멤버 화면 설정 시작
		 */
		final ListView memberGrid = (ListView)findViewById(R.id.listviewMemberList);
		
		ArrayList<MemberData> memberJsonData = new ArrayList<MemberData>();
		
		JSONArray json_result;
		try {
			json_result = JSONSharedPreferences.loadJSONArray(this, "gline", "memberInfo");
			
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				MemberData mList = new MemberData(jsonObject.getString("mem_name"), jsonObject.getString("mem_phone")
						,jsonObject.getString("mem_email"), jsonObject.getString("mem_birth")
						,jsonObject.getString("mem_desc")
				); 
				memberJsonData.add(mList);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.main_viewflow_sub3_listview_layout, memberJsonData);
		
		memListAdapter aa = new memListAdapter(this, R.layout.main_viewflow_sub3_listview_layout, memberJsonData);
		memberGrid.setAdapter(aa);
		
		memberGrid.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//view.setBackgroundColor(0x00);
				Log.d("C2DM", "Clicked" + position);
				//memberGrid.getChildAt(position).setBackgroundColor(0xFFFF0000);
            }
        });
		
		
		/*
		listView = (ListView) findViewById(R.id.listView1);
		String[] names = new String[] { "Cupcake", "Donut", "Eclair", "Froyo",
				"Gingerbread", "Honeycomb", "IceCream Sandwich"};
		// Create an ArrayAdapter, that will actually make the Strings above
		// appear in the ListView
		listView.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, names));
		*/
    }
    
    
    private void drawUI(Context context){
    	JSONArray json_result;
    	try {
    		json_result = JSONSharedPreferences.loadJSONArray(context, "gline", "memberInfo");
            Log.d("C2DM", "Birth Retrieve: " + json_result.length());
    		
    		Calendar today = Calendar.getInstance();
    	    String calCurrent;

    	    calCurrent = String.format("%02d", today.get(Calendar.MONTH) + 1);
    	    
    	    LinearLayout BirthList = (LinearLayout)findViewById(R.id.layoutBirthList);
    	    //LinearLayout MemberList = (LinearLayout)findViewById(R.id.layoutMemberList);
    	    
    	    BirthList.removeAllViews();
            
        	int j = 0;
        	LinearLayout BirthListSub = new LinearLayout(context);
            
            for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				MemberData tmp_nd = new MemberData();
				tmp_nd.setMemberName(jsonObject.getString("mem_name"));
				tmp_nd.setMemberPhone(jsonObject.getString("mem_phone"));
				tmp_nd.setMemberEmail(jsonObject.getString("mem_email"));
				tmp_nd.setMemberBirth(jsonObject.getString("mem_birth"));
				md_array.add(i, tmp_nd);
				
				//Log.d("C2DM", jsonObject.getString("mem_birth").substring(5,7) + " == " + calCurrent);
				
				if(jsonObject.getString("mem_birth").substring(5,7).equals(calCurrent)){
					
					if(j % 2 == 0){
						BirthListSub = new LinearLayout(context);
						BirthListSub.setOrientation(LinearLayout.HORIZONTAL);
					}
					
					TextView birthDateView = new TextView(context);
					birthDateView.setText(jsonObject.getString("mem_name") + "\n" + jsonObject.getString("mem_birth"));
					birthDateView.setTextColor(0xFFFFFFFF);
					birthDateView.setBackgroundColor(0xFF787974);
					birthDateView.setTextSize(15);
					birthDateView.setPadding(10, 10, 10, 10);
		    		
		    		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 0.5f);
		    		params.setMargins(1, 0, 1, 0);
		    		BirthListSub.addView(birthDateView, params);
		    		
		    		LayoutParams paramsSub = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		    		paramsSub.setMargins(0, 0, 0, 2);
		    		
		    		if(j % 2 == 0){
		    			BirthList.addView(BirthListSub, paramsSub);
					}
		    		j++;
				}
			}
			
			if( j == 0){
				TextView birthDateView = new TextView(context);
				birthDateView.setText("이달의 생일자가 없습니다.");
				birthDateView.setTextColor(0xFFFFFFFF);
				birthDateView.setTextSize(15);
				birthDateView.setPadding(10, 10, 10, 10);
				
				LayoutParams paramsSub = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
				BirthList.addView(birthDateView, paramsSub);
			}
    	} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	
    }
	
	private class initMainPage extends AsyncTask<Void, Void, Void> implements DialogInterface.OnCancelListener{
		private ProgressDialog dialog;
		private Context context;
		private JSONArray json_result;
		
		private initMainPage(Context context){
			this.context	= context;
		}

		protected void onPreExecute(){
			//dialog = ProgressDialog.show(context, "", "Loading. Please wait...", true);
		}

		protected Void doInBackground(Void... unused){
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
					
				JSONObject json = new JSONObject(hcm.readJSON(getString(R.string.SERVER_URL) + "members/member_list.php",null));
				Log.d("C2DM", "SERVICE_REQUEST: " + getString(R.string.SERVER_URL) + "members/member_list.php");
				
				json_result = json.getJSONArray("data_result");
				JSONSharedPreferences.saveJSONArray(context, "gline", "memberInfo", json_result);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
    		return null;
        }

        protected void onPostExecute(Void unused)
        {
            //dialog.dismiss();
            
            drawUI(context);
            

            //TextView mainNoticeViewHeader = (TextView)findViewById(R.id.mainNoticeViewHeader);
            //mainNoticeViewHeader.setText("최신공지사항: [" + tmp_nd.getReg_date() + "]" + tmp_nd.getTitle());
            
            //TextView mainNoticeView = (TextView)findViewById(R.id.mainNoticeView);
            //mainNoticeView.setText(tmp_nd.getContent());
        }

        public void onCancel(DialogInterface dialog)
        {
        	cancel(true);
        	dialog.dismiss();
        }
	}
	
	
	
	private class memListAdapter extends ArrayAdapter<MemberData> {

        private ArrayList<MemberData> items;
        
        
        public memListAdapter(Context context, int textViewResourceId, ArrayList<MemberData> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.main_viewflow_sub3_listview_layout, null);
            }
            
            MemberData p = items.get(position);
            
            if (p != null) {
                    TextView m1 = (TextView) v.findViewById(R.id.membName);
                    TextView m2 = (TextView) v.findViewById(R.id.membPhone);
                    TextView m3 = (TextView) v.findViewById(R.id.membBirth);
                    ImageButton ib = (ImageButton) v.findViewById(R.id.callButton);
                    
                    if(m1 != null)
                    	m1.setText(p.getMemberName());
                    if(m2 != null){
                    	String formattedNumber = PhoneNumberUtils.formatNumber(p.getMemberPhone());
                    	m2.setText(formattedNumber);
                    	//Linkify.addLinks(m2, Linkify.PHONE_NUMBERS);
                    	if(prefs.getString(PHONE_NO, "n/a").equals(p.getMemberPhone())){
                    		ib.setVisibility(View.INVISIBLE);
                    	}else{
                    		ib.setVisibility(View.VISIBLE);
                    		ib.setFocusable(false);
                    		ib.setOnClickListener(new phoneCallClickListner(p.getMemberPhone()));
                    	}
                    }
                    if(m3 != null)
                    	m3.setText(p.getMemberBirth());
                    
            }
            return v;
        }
	}
	
	private class phoneCallClickListner implements OnClickListener{
		private String phoneno;

	    public phoneCallClickListner(String phoneno) {
	       this.phoneno = phoneno;
	    }

	    public void onClick(View v) {
	    	try {
		        Intent callIntent = new Intent(Intent.ACTION_CALL);
		        callIntent.setData(Uri.parse("tel:" + phoneno));
		        startActivity(callIntent);
		    } catch (ActivityNotFoundException e) {
		         Log.e("C2DM", "Call failed", e);
		    }
	    }
	}
}
